package com.kdtech.analyse.blog;
import com.kdtech.crawler.CrawlHTML;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;


import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.analyse.AnalyseNews;

/**
 * 金融界博客
 * @author Persh
 *
 * 2014-7-8
 */
public class JrjBlogAnalyse implements AnalyseNews{

	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://blog.jrj.com.cn/[0-9]*,[a-z0-9]*.html",
				"http://blog.jrj.com.cn/[a-z]+,[0-9]+a.html",
				"http://blog.jrj.com.cn/[0-9]+\\%[A-Z0-9]+a.html",
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		String html = urlMeta.getHtml();
		if (html== null) {
		}
		NewsMeta blog = new NewsMeta();
		blog.setUrl(url);
		String title = null;
		String content = null;
		Long date = null;
		Integer clickNum=null;
		Integer commentNum=null;
		Integer deliverNum=null;
		String author=null;
		Document doc = Jsoup.parse(html);
		title  = doc.select("div.btit h1").text();
		date = DateUtils.matchDate(doc.select("span.eps").text());
		content = HtmlCleaner.getContentHtml(url,  doc.select("div.artcl"));
		author = doc.select("div.cont a.bon").text();
		String text = doc.select("div.article-statistics").text();
		clickNum = NumberUtils.matchNumber(StringUtils.substringBefore(text, "收藏"));
		commentNum = NumberUtils.matchNumber(StringUtils.substringAfter(text, "收藏"));

		blog.setTitle(title);
		blog.setContent(content);
		blog.setDate(date);
		blog.setAuthor(author);
		blog.setClickNum(clickNum);
		blog.setCommentNum(commentNum);
		//blog.setDeliverNum(deliverNum);
		blog.setUpdateUrl(url);
		return blog;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		String url = meta.getUpdateUrl();
		if (StringUtils.isNotBlank(url)){
			UrlMeta urlMeta = CrawlHTML.responseToURL(url);
			return parserHtml(urlMeta);
		}
		return null;
	}





	public static void main(String[] args) {
		String url = "http://blog.jrj.com.cn/zengguoxing,15049066a.html";
		JrjBlogAnalyse test = new JrjBlogAnalyse();
		if(test.isDetailPage(url)){
			UrlMeta responseToURL = CrawlHTML.responseToURL(url);
			NewsMeta parserHtml = test.parserHtml(responseToURL);
			System.out.println(parserHtml);
//			System.out.println(test.Update(parserHtml));
		}else{
			System.out.println("不符合规则");
		}
	}

	
}
